package org.zw.store.pub.api;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.zw.store.common.Result;
import org.zw.store.common.StoreConstants;
import org.zw.store.common.TokenUser;
import org.zw.store.common.TokenUtils;
import org.zw.store.pub.dao.PublicDao;
import org.zw.store.pub.dto.AdminLoginDto;
import org.zw.store.pub.model.Admin;
import org.zw.store.pub.model.Cls;

import java.io.*;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/public")
public class PublicAPI {

    @Autowired
    private PublicDao publicDao;

    @GetMapping("/img/{imgname}") // {imgname}路径参数
    public void img(@PathVariable String imgname, OutputStream out) throws IOException {//@PathVariable说明参数来源于路径中

        String path = StoreConstants.UPLOAD_DIR + "/" + imgname;
        byte[] b = new byte[1024];
        int len = -1;
        FileInputStream in = new FileInputStream(path);
        while ((len = in.read(b)) != -1) {
            out.write(b, 0, len);
        }
        out.flush();
        out.close();
        in.close();
    }

    @GetMapping("/cls")
    public Result<List<Cls>> clsList() {
        List<Cls> clsList = publicDao.findClsList();
        return Result.OK(clsList);
    }

    /*@PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        String filename = UUID.randomUUID().toString().replace("-","");
        log.debug("filename======>{}", filename);

        InputStream in = null;
        FileOutputStream out = null;

        try {
            in = file.getInputStream();
            out = new FileOutputStream(StoreConstants.UPLOAD_DIR + "/" + filename);
            byte[] b = new byte[1024];
            int len = -1;
            while((len= in.read()) != -1){
                out.write(b,0,len);
            }
            out.flush();
            return Result.OK("上传成功",filename);
        } finally {
            try {
                if(out!=null)out.close();
            } catch (IOException e) {}
            try {
                if(in!=null)in.close();
            } catch (IOException e) {}
        }

    }*/

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {

        String originalFilename = file.getOriginalFilename();

        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID() + suffix;

        //目录不存在的话创建一个目录
        /*File dir = new File(basePath);
        if(!dir.exists()){
            dir.mkdirs();
        }*/

        try {
            file.transferTo(new File(StoreConstants.UPLOAD_DIR + "/" + fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.OK("上传成功",fileName);
    }

    @PostMapping("/admin/login")
    public Result<String> adminLogin(@RequestBody AdminLoginDto adminLoginDto){
        Admin admin = publicDao.findAdminByIdAndPwd(adminLoginDto);
        if(admin != null){ //登录成功
            TokenUser tokenUser = TokenUser.createAdmin(admin.getA_id(), admin.getA_name(),
                    admin.getShop_id(), admin.getShop_name());

            String token = TokenUtils.loginSign(tokenUser);
            return Result.OK("登录成功",token);
        }

        //登录失败
        return Result.ERR(Result.CODE_ERR_BUSINESS,"登录失败");
    }
}
